import { useCallback, useEffect, useState } from 'react';

import { BigNumber } from 'ethers';
import useBasisCash from './useBasisCash';
import { ContractName } from '../basis-cash';
import config from '../config';
import { ethers } from 'ethers';

const useVoterCount = (contract: string) => {
  const [balance, setBalance] = useState(0);
  const basisCash = useBasisCash();

  const fetchBalance = useCallback(async () => {
    const balance = await basisCash.contracts[contract].getVoterCount();
    const vote = Number(ethers.utils.formatUnits(balance, 0));
    setBalance(vote);
  }, [basisCash?.isUnlocked]);

  useEffect(() => {
    if (basisCash?.isUnlocked) {
      fetchBalance().catch(err => console.error('useVoterCount',err.stack));

      const refreshBalance = setInterval(fetchBalance, config.refreshInterval);
      return () => clearInterval(refreshBalance);
    }
  }, [basisCash?.isUnlocked, setBalance, basisCash]);

  return balance;
};

export default useVoterCount;
